﻿using System;
using System.IO;
using System.Text;
using System.Xml;

namespace MockingBird.Common.Infrastructure.Soap
{
    public class SoapRequest
    {
        private string envelope;
        private string header;
        private string body;

        public string Action { get; set; }

        public SoapRequest()
        {
            header = String.Empty;
            body = string.Empty;

        }

        public void AddHeader(string headerXml)
        {
            this.header = headerXml;
        }

        public void AddHeader(XmlDocument headerDoc)
        {
            AddHeader(headerDoc.OuterXml);
        }

        public void AddBody(string bodyXml)
        {
            this.body = bodyXml;
        }

        public void AddBody(XmlDocument bodyDoc)
        {
            AddBody(bodyDoc.OuterXml);
        }

        public void AddBody(Uri bodyFilePath)
        {
            AddBody(File.ReadAllText(bodyFilePath.AbsolutePath));
        }

        public byte[] Get()
        {
            return Get(Encoding.UTF8);
        }

        public byte[] Get(Encoding targetEncoding)
        {
            ConstructEnvelope();
            return targetEncoding.GetBytes(envelope);

        }

        private void ConstructEnvelope()
        {
            envelope = "<?xml version=\"1.0\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
            if (header.Length > 0)
            {
                envelope = envelope + "<soap:Header>" + header + "</soap:Header>";
            }
            if (body.Length > 0)
            {
                envelope = envelope + "<soap:Body>" + body + "</soap:Body>";
            }
            envelope = envelope + "</soap:Envelope>";

        }

    }
}
